package com.alageek.gulimall.product.service.impl;

import com.alageek.common.constant.ProductConstant;
import com.alageek.gulimall.product.entity.AttrAttrgroupRelationEntity;
import com.alageek.gulimall.product.entity.AttrGroupEntity;
import com.alageek.gulimall.product.entity.CategoryEntity;
import com.alageek.gulimall.product.service.AttrAttrgroupRelationService;
import com.alageek.gulimall.product.service.AttrGroupService;
import com.alageek.gulimall.product.service.CategoryService;
import com.alageek.gulimall.product.vo.AttrRespVo;
import com.alageek.gulimall.product.vo.AttrVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.alageek.common.utils.PageUtils;
import com.alageek.common.utils.Query;

import com.alageek.gulimall.product.dao.AttrDao;
import com.alageek.gulimall.product.entity.AttrEntity;
import com.alageek.gulimall.product.service.AttrService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Autowired
    private AttrAttrgroupRelationService relationService;

    @Autowired
    private AttrGroupService attrGroupService;

    @Autowired
    private CategoryService categoryService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<>()
        );
        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void saveAttr(AttrVo attr) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr, attrEntity);
        // 保存基本数据
        save(attrEntity);
        // 保存关联关系
        if (attr.getAttrGroupId() != null) {
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            relationEntity.setAttrId(attrEntity.getAttrId());
            relationEntity.setAttrGroupId(attr.getAttrGroupId());
            relationService.save(relationEntity);
        }
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params, Long catelogId, String attrType) {
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<>();
        if (catelogId != 0) {
            wrapper.eq("catelog_id", catelogId);
        }
        if (ProductConstant.AttrEnum.ATTR_TYPE_BASE.getType().equals(attrType)) {
            wrapper.eq("attr_type", ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode());
        } else if (ProductConstant.AttrEnum.ATTR_TYPE_SALE.getType().equals(attrType)) {
            wrapper.eq("attr_type", ProductConstant.AttrEnum.ATTR_TYPE_SALE.getCode());
        }
        String key = (String) params.get("key");
        if (StringUtils.hasText(key)) {
            wrapper.and((obj) -> {
                obj.eq("attr_id", key).or().like("attr_name", key);
            });
        }
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                wrapper
        );
        List<AttrRespVo> respVos = page.getRecords().stream().map(attrEntity -> {
            AttrRespVo attrRespVo = new AttrRespVo();
            BeanUtils.copyProperties(attrEntity, attrRespVo);
            // 查询所属分类名字
            CategoryEntity categoryEntity = categoryService.getById(attrEntity.getCatelogId());
            if (categoryEntity != null) {
                attrRespVo.setCatelogName(categoryEntity.getName());
            }
            // 查询所属分组名字
            AttrAttrgroupRelationEntity relationEntity = relationService.getOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrEntity.getAttrId()));
            if (relationEntity != null && relationEntity.getAttrGroupId() != null) {
                AttrGroupEntity attrGroupEntity = attrGroupService.getById(relationEntity.getAttrGroupId());
                if (attrGroupEntity != null) {
                    attrRespVo.setGroupName(attrGroupEntity.getAttrGroupName());
                }
            }
            return attrRespVo;
        }).collect(Collectors.toList());
        PageUtils pageUtils = new PageUtils(page);
        pageUtils.setList(respVos);
        return pageUtils;
    }

    @Override
    public AttrRespVo getAttrInfo(Long attrId) {
        AttrRespVo attrRespVo = new AttrRespVo();
        AttrEntity attrEntity = getById(attrId);
        BeanUtils.copyProperties(attrEntity, attrRespVo);
        // 查询所属分组id
        AttrAttrgroupRelationEntity relationEntity = relationService.getOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrEntity.getAttrId()));
        if (relationEntity != null) {
            attrRespVo.setAttrGroupId(relationEntity.getAttrGroupId());
        }
        // 查询所属分类完整路径
        attrRespVo.setCatelogPath(categoryService.findCatelogPath(attrEntity.getCatelogId()));
        return attrRespVo;
    }

    @Transactional
    @Override
    public void updateAttr(AttrVo attr) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr, attrEntity);
        // 保存基本数据
        updateById(attrEntity);
        // 保存关联关系
        if (attr.getAttrGroupId() != null) {
            AttrAttrgroupRelationEntity relationEntity = relationService.getOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrEntity.getAttrId()));
            if (relationEntity == null) {
                relationEntity = new AttrAttrgroupRelationEntity();
                relationEntity.setAttrId(attrEntity.getAttrId());
                relationEntity.setAttrGroupId(attr.getAttrGroupId());
                relationService.save(relationEntity);
            } else {
                relationEntity.setAttrGroupId(attr.getAttrGroupId());
                relationService.updateById(relationEntity);
            }
        }
    }

    @Override
    public List<AttrEntity> getAttrRelation(Long attrGroupId) {
        List<AttrAttrgroupRelationEntity> relationEntityList = relationService.list(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id", attrGroupId));
        if (relationEntityList == null || relationEntityList.size() == 0) {
            return null;
        } else {
            List<Long> attrIds = relationEntityList.stream().map(AttrAttrgroupRelationEntity::getAttrId).collect(Collectors.toList());
            return (List<AttrEntity>) listByIds(attrIds);
        }
    }

    @Override
    public PageUtils getNoAttrRelation(Map<String, Object> params, Long attrGroupId) {
        // 1、查询当前分组所属分类
        AttrGroupEntity attrGroupEntity = attrGroupService.getById(attrGroupId);
        if (attrGroupEntity != null) {
            Long catelogId = attrGroupEntity.getCatelogId();
            // 2.1 找到该分类下所有分组
            List<AttrGroupEntity> attrGroupEntities = attrGroupService.list(new QueryWrapper<AttrGroupEntity>().eq("catelog_id", catelogId));
            List<Long> attrGroupIds = attrGroupEntities.stream().map(AttrGroupEntity::getAttrGroupId).collect(Collectors.toList());
            // 2.2 找到该分类下所有已经关联的属性
            List<Long> attrIds = null;
            List<AttrAttrgroupRelationEntity> relationEntities = relationService.list(new QueryWrapper<AttrAttrgroupRelationEntity>().in("attr_group_id", attrGroupIds));
            if (relationEntities != null && relationEntities.size() > 0) {
                attrIds = relationEntities.stream().map(AttrAttrgroupRelationEntity::getAttrId).collect(Collectors.toList());
            }
            // 2.3 查找该分类下所有未被关联的属性
            QueryWrapper<AttrEntity> wrapper = new QueryWrapper<AttrEntity>().eq("catelog_id", catelogId).eq("attr_type", ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode());
            if (attrIds != null && attrIds.size() > 0) {
                wrapper.notIn("attr_id", attrIds);
            }
            String key = (String) params.get("key");
            if (StringUtils.hasText(key)) {
                wrapper.and((obj) -> {
                    obj.eq("attr_id", key).or().like("attr_name", key);
                });
            }
            IPage<AttrEntity> page = this.page(
                    new Query<AttrEntity>().getPage(params),
                    wrapper
            );
            return new PageUtils(page);
        } else {
            return null;
        }
    }

    /**
     * 查询可检索的属性
     */
    @Override
    public List<Long> selectSearchAttrIds(List<Long> attrIds) {
        return this.baseMapper.selectSearchAttrIds(attrIds);
    }

}